package cvo.chess.client.ui.movement;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

import cvo.chess.client.entities.GameFacade;

public class MovementControlerWidget extends Composite {

	private static MovementControlerWidgetUiBinder uiBinder = GWT
			.create(MovementControlerWidgetUiBinder.class);

	interface MovementControlerWidgetUiBinder extends
			UiBinder<Widget, MovementControlerWidget> {
	}

	private GameFacade gf;

	public MovementControlerWidget(GameFacade gf) {
		initWidget(uiBinder.createAndBindUi(this));
		this.gf = gf;
	}

	@UiField
	Button button;
	@UiField
	TextBox nextMove;

	public MovementControlerWidget(String firstName) {
		initWidget(uiBinder.createAndBindUi(this));
		button.setText(firstName);
	}

	@UiHandler("button")
	void onClick(ClickEvent e) {
		try {
			String move = nextMove.getValue();
			// TODO: input validation (Also for algebraicNotation)
			String from = move.substring(0, 2); //Remember, he beginIndex is inclusive, the endIndex is exclusive (dan't ask me why...) 
			String to = move.substring(3, 5);

			gf.doMove(from, to);
		} catch (Exception ex) {
			Window.alert(ex.getLocalizedMessage());
		}

	}

}
